'''
Created on Nov 25, 2010

@author: Polido
'''

import serial
import math

class Serial(object):
    '''
    classdocs
    '''


    def __init__(self, port, baudrate):
        '''
        Constructor
        '''
        self.portName = port
        self.baudRate = baudrate
        
        self.Serial = serial.Serial(port=self.portName, baudrate=self.baudRate, timeout=1)
        self.ChecksumBytes = []
        
    def writeNormalized(self, val, min, max):
        
        writeVal = val - min
        writeVal /= max - min
        
        if writeVal > 1.0:
            print "Error! Writing a value bigger than than max(" + max + ")"
            writeVal = 1.0
        elif writeVal < 0.0:
            print "Error! Writing a value smaller than than min(" + max + ")"
            writeVal = 0.0
        
        writeVal *= 255.0
        
        self.write(chr(int(math.floor(writeVal))))
        
    def write(self, data):
        self.Serial.write(data)
        self.ChecksumBytes.append(data)
        
    def start(self):
        self.ChecksumBytes = []
        
    def finish(self):
        sum = 0
        
        for byte in self.ChecksumBytes:
            sum += ord(byte)
            
        self.Serial.write(chr(sum & 0xFF))
        
    def available(self):
        return self.Serial.inWaiting()
    
    def readall(self):
        return self.Serial.read( self.available() )
    
    def Remove(self):
        self.Serial.close()
